<template>
	<view class="wrapper order">
		<u-loading-page loadingColor="#e3230e" iconSize="40" :loading="isPageLoading"></u-loading-page>
		<view class="order-tabs main-flex">
			<view class="main-flex-item" v-show="orderItems.length > 0">
				<uni-segmented-control
					:current="current"
					:values="orderItems"
					@clickItem="onClickItem"
					styleType="button"
					activeColor="#e3230e"></uni-segmented-control>
			</view>
		</view>
		
		<swiper
			@change="changeSwiper"
			:current="current"
			class="swiper">
			<swiper-item
				v-for="(item, index) in childList"
				:key="item.id">
				<scroll-view class="swiper-item" scroll-y>
					<view class="swiper-item-content order-safe-area">
					<view class="order-box">
						<view class="order-item main-flex" v-if="item.order.salesmanName">
							<view class="order-item-l main-flex">
								<text class="order-item-name">客户经理：</text>
								<text class="order-item-text">{{item.order.salesmanName}}</text>
							</view>
							<view class="order-item-r main-flex">
								<text class="order-item-name">联系电话：</text>
								<text class="order-item-text">{{item.order.salesmanPhone}}</text>
								<!-- <image class="order-item-icon" @click="copyText(item.order.salesmanPhone)" src="/static/images/icon/copy.png"></image> -->
								<image class="order-item-icon" @click="callPhone(item.order.salesmanPhone)" src="/static/images/icon/call.png"></image>
							</view>
						</view>
						<view class="order-item main-flex">
							<view class="order-item-l main-flex">
								<text class="order-item-name">配送仓：</text>
								<text class="order-item-text">{{item.order.warehouseName}}</text>
							</view>
							<view class="order-item-r main-flex">
								<text class="order-item-name">配送电话：</text>
								<text class="order-item-text">{{item.order.warehousePhone}}</text>
								<!-- <image class="order-item-icon" @click="copyText(item.order.warehousePhone)" src="/static/images/icon/copy.png"></image> -->
								<image class="order-item-icon" @click="callPhone(item.order.warehousePhone)" src="/static/images/icon/call.png"></image>
							</view>
						</view>
						<view class="order-item main-flex">
							<view class="order-item-r main-flex-item main-flex">
								<text class="order-item-name">客服电话：</text>
								<text class="order-item-text">{{setStore?.sys?.customer_service}}</text>
								<!-- <image class="order-item-icon" @click="copyText(setStore?.sys?.customer_service)" src="/static/images/icon/copy.png"></image> -->
								<image class="order-item-icon" @click="callPhone(setStore?.sys?.customer_service)" src="/static/images/icon/call.png"></image>
							</view>
						</view>
					</view>
					
					<view class="order-box" v-if="item?.express?.nu">
						<view class="express-item main-flex" @click="goExpress(item.order)">
							<image class="express-item-icon" mode="heightFix" src="/static/images/icon/send.png"></image>
							<text class="express-item-text">{{item?.express?.companyName}}</text>
							<text class="express-item-text">{{item?.express?.nu}}</text>
							<uni-icons class="express-item-right" type="right" size="20" color="#333333"></uni-icons>
						</view>
						<view class="express-item" v-if="item?.express?.data?.[0]">
							<view class="express-item-context">{{item?.express?.data[0].context}}</view>
							<view class="express-item-time">{{item?.express?.data[0].time}}</view>
						</view>
					</view>
					<view class="order-box" v-if="item.order.status === 2 && !item?.express?.nu">
						<view class="express-item">
							<view class="express-item-start">订单配送中</view>
						</view>
					</view>
					
					<view class="order-box">
						<view class="order-item main-flex">
							<uni-icons class="order-item-send" type="location" size="20" color="#333333"></uni-icons>
							<text class="order-item-text1">{{item.order.contacts}}</text>
							<text class="order-item-text1">{{item.order.addrPhone}}</text>
						</view>
						<view class="order-item main-flex">
							<text class="order-item-name">地址：{{item.order.addressDetail}}</text>
						</view>
					</view>
					
					<view class="order-box">
						<view class="order-item main-flex">
							<view class="order-item-r main-flex-item main-flex">
								<text class="order-item-name">订单编号：</text>
								<text class="order-item-text">{{item.order.orderNumber}}</text>
								<image class="order-item-icon" @click="copyText(item.order.orderNumber)" src="/static/images/icon/copy.png"></image>
							</view>
						</view>
						<view class="order-item main-flex">
							<view class="order-item-r main-flex-item main-flex">
								<text class="order-item-name">下单时间：</text>
								<text class="order-item-text">{{item.order.createTime}}</text>
							</view>
						</view>
						<view class="order-item main-flex" v-if="item.order?.capitalDetail?.createTime">
							<view class="order-item-r main-flex-item main-flex">
								<text class="order-item-name">付款时间：</text>
								<text class="order-item-text">{{item.order.capitalDetail.createTime}}</text>
							</view>
						</view>
						<view class="order-item main-flex" v-if="item.order?.sendTime">
							<view class="order-item-r main-flex-item main-flex">
								<text class="order-item-name">发货时间：</text>
								<text class="order-item-text">{{item.order.sendTime}}</text>
							</view>
						</view>
						<view class="order-item main-flex" v-if="item.order?.capitalDetail?.remark">
							<view class="order-item-r main-flex-item main-flex flex-start">
								<text class="order-item-name">支付方式：</text>
								<text class="order-item-text main-flex-item">{{item.order.capitalDetail.remark}}</text>
							</view>
						</view>
						<view class="order-item main-flex" v-if="item.order?.remark">
							<view class="order-item-r main-flex-item main-flex flex-start">
								<text class="order-item-name">备注：</text>
								<text class="order-item-text main-flex-item">{{item.order?.remark}}</text>
							</view>
						</view>
					</view>
					
					<view class="order-box">
						<view class="goods-item main-flex" v-for="(child, childIndex) in item.order.productList" :key="childIndex">
							<view class="goods-item-l">
								<image class="goods-item-pic" :src="imgUrl(child.productImg)" lazy-load></image>
							</view>
							<view class="goods-item-c main-flex-item">
								<view class="goods-item-name">{{child.productName}}</view>
								<view class="goods-item-count">数量：{{child.number}}</view>
								<view class="goods-item-price">单价：￥{{child.price}}/{{child.productUnit}}</view>
							</view>
							<view class="goods-item-r main-flex">
								<view class="goods-item-money">￥{{moneyStr(child.money)}}</view>
							</view>
						</view>
					</view>
					
					<view class="order-box">
						<view class="money-item main-flex">
							<view class="money-item-name">商品总额</view>
							<view class="money-item-num">￥{{item.order?.originalPrice || '0.00'}}</view>
						</view>
						<view class="money-item main-flex" v-if="index === 0">
							<view class="money-item-name">运费</view>
							<view class="money-item-num">￥{{item.order?.freight || '0.00'}}</view>
						</view>
						<view class="money-item main-flex" v-if="index === 0">
							<view class="money-item-name">优惠券</view>
							<view class="money-item-num">-￥{{item.order?.discountPrice || '0.00'}}</view>
						</view>
						<view class="money-item main-flex" v-if="index === 0">
							<view class="money-item-name">专享折扣折</view>
							<view class="money-item-num">-￥{{item.order?.balancePrice || '0.00'}}</view>
						</view>
						<view class="money-item main-flex">
							<view class="money-item-name">实付款</view>
							<view class="money-item-num price">￥{{item.order?.actualPrice || '0.00'}}</view>
						</view>
						<view class="money-item main-flex" v-if="item.order.status === 4">
							<view class="money-item-name">已退款</view>
							<view class="money-item-num price">￥{{item.order?.refundPrice || '0.00'}}</view>
						</view>
						<view class="money-item main-flex" v-if="index === 0">
							<view class="money-item-name">总订单合计</view>
							<view class="money-item-num price">￥{{allActualPrice || '0.00'}}</view>
						</view>
					</view>
					
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		
		
		
		<view class="order-btns safe-area" v-if="childList?.[current]">
			<view class="order-btns-box main-flex">
				<view class="order-btns-status" :class="`order-status${childList?.[current]?.order?.status}`">{{arrText(orderStatusList, childList?.[current]?.order?.status)}}</view>
				<button @click="cancelOrder(childList?.[current]?.order)" class="ty-button ty-button-plain-cancel order-btns-btn" v-if="childList?.[current]?.order?.status === 0">取消订单</button>
				<button @click="payOrder(childList?.[current]?.order)" class="ty-button ty-button-plain-confirm order-btns-btn" v-if="childList?.[current]?.order?.status === 0">立即付款</button>
				<button @click="goExpress(childList?.[current]?.order)" class="ty-button ty-button-plain-warning order-btns-btn" v-if="childList?.[current]?.order?.status === 2">查看物流</button>
				<button @click="confirmReceipt(childList?.[current]?.order)" class="ty-button ty-button-plain-confirm order-btns-btn" v-if="childList?.[current]?.order?.status === 2">确认收货</button>
				<button @click="goService" class="ty-button ty-button-plain-confirm order-btns-btn service">
					<image class="order-btns-btn-icon" src="/static/images/icon/weixin.png"></image>
					<text>联系售后</text>
				</button>
			</view>
		</view>
		
		<pay
			:showPay="showPay"
			:order="orderInfo"
			@success="successPay"
			@close="closePay"></pay>
		
	</view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide, onUnload, onBackPress } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { throttle, debounce, sleep } from '@/uni_modules/uview-plus'
import { orderDetail, orderCancel, orderExpress, orderConfirmReceipt } from "@/api/app_api/order"
import { Decimal } from 'decimal.js'
import modal from '@/plugins/modal'
import { orderStatusList } from '@/utils/config'
import { arrText, serviceWeixin } from '@/utils/ty'
import index from '../../plugins';

	const userStore = useUserStore()
	const setStore = useSetStore()
	
	const ids = ref('')
	const isPageLoading = ref(true)
	onLoad((option) => {
		ids.value = option?.id.split(',') || []
		if (ids.value.length > 1) {
			getChildDetail()
		}
	})
	const childList = ref([])
	const getChildDetail = async () => {
		for(let i = 0; i < ids.value.length; i++ ) {
			const res = await orderDetail({id: ids.value[i]})
			if (res?.data) {
				if (res.data?.productList) {
					res.data.productList = res.data.productList.map(item => {
						return {
							...item,
							money: Decimal(item.price).mul(Decimal(item.number)).toNumber()
						}
					})
				}
				let exp = null
				if (res.data?.expressNumber) {
					exp = await orderExpressDetail(ids.value[i])
				}
				childList.value.push({
					order: res.data,
					express: exp || null
				})
			}
			if (i === ids.value.length - 1) {
				isPageLoading.value = false
			}
		}
	}
	
	// 获取物流信息
	const orderExpressDetail = (id) => {
		return new Promise((resolve, reject) => {
			orderExpress({
				id: id
			}).then(res => {
				if (res?.data) {
					resolve(res.data)
				} else {
					resolve(null)
				}
			}).catch(err => {
				resolve(null)
			})
		}) 
	}
	
	// 取消订单
	const cancelOrder = (order) => {
		uni.showModal({
			title: '取消订单',
			content: '确认取消此订单吗？',
			success: function (res) {
				if (res.confirm) {
					cancelOrderFun(order.id)
				} else if (res.cancel) {
					
				}
			}
		})
	}
	const isCancel = ref(false)
	const cancelOrderFun = (id) => {
		if (isCancel.value) return false
		isCancel.value = true
		orderCancel({
			id
		}).then(res => {
			uni.$u.toast('订单已取消')
			uni.$u.sleep(1000).then(() => {
				isCancel.value = false
				uni.navigateBack({
					delta: 1
				})
				uni.$emit('refresh');  // 触发刷新事件
			})
		}).catch(() => {
			isCancel.value = false
		})
	}
	
	// 确认收货
	const confirmReceipt = (order) => {
		uni.showModal({
			title: '确认收货',
			content: '确认收到货物了吗？',
			success: function (res) {
				if (res.confirm) {
					confirmReceiptFun(order.id)
				} else if (res.cancel) {
					
				}
			}
		})
	}
	const isConfirmReceipt = ref(false)
	const confirmReceiptFun = (id) => {
		if (isConfirmReceipt.value) return false
		isConfirmReceipt.value = true
		orderConfirmReceipt({
			id
		}).then(res => {
			uni.$u.toast('订单已收货')
			uni.$u.sleep(1000).then(() => {
				isConfirmReceipt.value = false
				uni.navigateBack({
					delta: 1
				})
				uni.$emit('refresh');  // 触发刷新事件
			})
		}).catch(() => {
			isConfirmReceipt.value = false
		})
	}
	
	// 客服
	const goService = () => {
		serviceWeixin()
	}
	
	// 查看物流
	const goExpress = (order) => {
		uni.navigateTo({
			url: `/pages/order/express?id=${order.id}`
		})
	}
	
	// 支付相关
	const isPayOrder = ref(false)
	const showPay = ref(false)
	const orderInfo = ref({})
	const payOrder = (order) => {
		orderInfo.value = {...order}
		showPay.value = true
	}
	const closePay = () => {
		showPay.value = false
	}
	const successPay = () => {
		getDetail()
		uni.$emit('refresh');  // 触发刷新事件
	}
	
	
	const current = ref(0)
	const items = []
	const onClickItem = (e) => {
		current.value = e.currentIndex
	}
	const changeSwiper = (e) => {
		current.value = e.detail.current
	}
	
	const orderItems = computed(() => {
		return childList.value.map((item, index) => {
			return index === 0 ? '主订单' : `子订单${index}`
		})
	})
	
	const allActualPrice = computed(() => {
		return childList.value.reduce((prev, cur, index, arr)=> {
				return Decimal(prev).add(Decimal(cur.order.actualPrice)).toNumber()
			}, 0)
	})
	
	watch(() => userStore.user.id, (nval, oval) => {
		if (nval) {
			getDetail()
		}
	})
	
</script>

<style lang="scss" scoped>
	.order {
		height: 100%;
		box-sizing: border-box;
		&-box {
			border-radius: 20rpx;
			background-color: #ffffff;
			padding: 20rpx;
			&+.order-box {
				margin-top: 20rpx;
			}
		}
		&-item {
			font-size: 24rpx;
			&+.order-item {
				margin-top: 10rpx;
			}
			&-l {
				width: 280rpx;
			}
			&-name {
				color: $text-light;
			}
			&-send {
				margin-right: 20rpx;
			}
			&-text {
				// flex: 1;
				overflow: hidden;
				word-break: break-all;
			}
			&-text1 {
				font-size: 28rpx;
				margin-right: 20rpx;
			}
			&-icon {
				width: 32rpx;
				height: 32rpx;
				margin-left: 20rpx;
			}
		}
		&-tabs {
			position: fixed;
			height: 80rpx;
			width: 100%;
			left: 0;
			background-color: #ffffff;
			z-index: 10;
			padding: 0 20rpx;
			box-sizing: border-box;
		}
		.swiper {
			width: 100%;
			height: 100vh;
			/* #ifdef WEB */
			height: calc(100vh - 44px);
			height: calc(100vh - 44px - constant(safe-area-inset-top));
			height: calc(100vh - 44px - env(safe-area-inset-top));
			/* #endif */
			&-item {
				height: 100%;
				box-sizing: border-box;
				padding: 20rpx;
				&-content {
					padding-top: 80rpx;
				}
			}
		}
		.goods-item {
			align-items: flex-start;
			&+.goods-item {
				margin-top: 20rpx;
			}
			&-l {
				width: 160rpx;
				height: 160rpx;
				overflow: hidden;
				border-radius: 10rpx;
			}
			&-pic {
				width: 160rpx;
				height: 160rpx;
			}
			&-c {
				padding: 0 10rpx;
			}
			&-r {
				height: 160rpx;
				align-items: center;
				padding: 0 10rpx;
			}
			&-name {
				font-size: 26rpx;
				font-weight: 600;
				word-break: break-all;
			}
			&-count {
				font-size: 24rpx;
				color: $text-light;
				margin-top: 4rpx;
			}
			&-price {
				font-size: 24rpx;
				color: $text-light;
				margin-top: 4rpx;
			}
			&-money {
				font-size: 32rpx;
				color: $primary-color;
				text-align: right;
			}
		}
		.money-item {
			&+.money-item {
				margin-top: 10rpx;
			}
			&-name {
				font-size: 26rpx;
			}
			&-num {
				font-size: 28rpx;
				color: #000000;
				font-weight: 600;
				margin-left: auto;
			}
			.price {
				font-size: 32rpx;
			}
		}
		&-btns {
			position: fixed;
			width: 100%;
			left: 0;
			bottom: 0;
			background-color: #ffffff;
			box-sizing: border-box;
			&-box {
				width: 100%;
				padding: 20rpx;
				box-sizing: border-box;
				justify-content: flex-end;
			}
			&-status {
				margin-left: auto;
				color: $primary-color;
				font-size: 30rpx;
				font-weight: 600;
				margin-right: auto;
				margin-left: 0rpx;
			}
			.status5 {
				color: $text-light;
			}
			&-btn {
				width: 150rpx;
				height: 48rpx;
				background-color: #ffffff;
				padding: 0;
				margin: 0;
				font-size: 20rpx;
				justify-content: center;
				margin-left: 20rpx;
				border-radius: 24rpx;
				&-icon {
					width: 28rpx;
					height: 28rpx;
					margin-right: 10rpx;
				}
				&+.service {
					display: none;
				}
			}
		}
		.express-item {
			&+.express-item {
				margin-top: 20rpx;
			}
			&-start {
				font-size: 40rpx;
				font-weight: 600;
			}
			&-icon {
				height: 28rpx;
				margin-right: 20rpx;
			}
			&-text {
				font-size: 28rpx;
				margin-right: 20rpx;
			}
			&-right {
				margin-left: auto;
			}
			&-context {
				font-size: 24rpx;
				color: $text-light;
			}
			&-time {
				font-size: 24rpx;
				color: $text-light;
				text-align: right;
			}
		}
	}
	.order-safe-area {
		padding-bottom: calc(constant(safe-area-inset-bottom) + 88rpx); /* 兼容iOS <11.2 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 88rpx); /* 兼容iOS ≥11.2 */
	}
</style>
